//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";
import type { EvaluateInfo, EVALUATE_STATE } from "@/api/org_evaluate";
import { EVALUATE_STATE_DRAFT, EVALUATE_STATE_EVALUATE, EVALUATE_STATE_FINISH, list_evaluate, get_evaluate, update_state_for_evaluate, remove_evaluate } from "@/api/org_evaluate";
import { request } from "@/utils/request";
import type { ColumnsType } from 'antd/lib/table';
import { Button, message, Modal, Space, Table, Tag } from "antd";
import UserPhoto from "@/components/Portrait/UserPhoto";
import EditEvalModal from "./EditEvalModal";
import ViewEvalModal from "./ViewEvalModal";

const PAGE_SIZE = 10;

export interface EvalListProps {
    departMentId: string;
    memberUserId?: string;
    dataVersion: number;
}

const EvalList = (props: EvalListProps) => {
    const userStore = useStores("userStore");
    const orgStore = useStores("orgStore");

    const [evalInfoList, setEvalInfoList] = useState<EvaluateInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [editEvaluateInfo, setEditEvaluateInfo] = useState<EvaluateInfo | null>(null);
    const [removeEvaluateInfo, setRemoveEvaluateInfo] = useState<EvaluateInfo | null>(null);
    const [viewEvaluateInfo, setViewEvaluateInfo] = useState<EvaluateInfo | null>(null);

    const loadEvalInfoList = async () => {
        const res = await request(list_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            depart_ment_id: props.departMentId,
            filter_member_user_id: props.memberUserId !== undefined,
            member_user_id: props.memberUserId ?? "",
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        setEvalInfoList(res.evaluate_list);
    };

    const onUpdate = async (evalId: string) => {
        const tmpList = evalInfoList.slice();
        const index = tmpList.findIndex(item => item.evaluate_id == evalId);
        if (index == -1) {
            return;
        }
        const res = await request(get_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            evaluate_id: evalId,
        }));
        tmpList[index] = res.evaluate;
        setEvalInfoList(tmpList);
    };

    const onVoteChange = async () => {
        if (viewEvaluateInfo == null) {
            return;
        }
        const tmpList = evalInfoList.slice();
        const index = tmpList.findIndex(item => item.evaluate_id == viewEvaluateInfo.evaluate_id);
        if (index == -1) {
            return;
        }
        const res = await request(get_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            evaluate_id: viewEvaluateInfo.evaluate_id,
        }));
        tmpList[index] = res.evaluate;
        setEvalInfoList(tmpList);
        setViewEvaluateInfo(res.evaluate);
    };

    const changeState = async (evalId: string, newState: EVALUATE_STATE) => {
        await request(update_state_for_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            evaluate_id: evalId,
            state: newState,
        }));
        message.info("更新成功");
        await onUpdate(evalId);
    };

    const removeEval = async () => {
        if (removeEvaluateInfo == null) {
            return;
        }
        await request(remove_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            evaluate_id: removeEvaluateInfo.evaluate_id,
        }));
        message.info("删除成功");
        setRemoveEvaluateInfo(null);
        await loadEvalInfoList();
    };

    const columns: ColumnsType<EvaluateInfo> = [
        {
            title: "名称",
            width: 100,
            dataIndex: "evaluate_title",
        },
        {
            title: "评估要求",
            render: (_, row: EvaluateInfo) => (
                <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>{row.evaluate_desc}</pre>
            ),
        },
        {
            title: "评估指标",
            width: 100,
            render: (_, row: EvaluateInfo) => (
                <Space style={{ flexWrap: "wrap" }}>
                    {row.member_list.length > 0 && row.member_list[0].score_list.map(item => (
                        <Tag key={item.target_id}>{item.target_name}</Tag>
                    ))}
                </Space>
            ),
        },
        {
            title: "参与人员",
            width: 200,
            render: (_, row: EvaluateInfo) => (
                <Space style={{ flexWrap: "wrap" }}>
                    {row.member_list.map(item => (
                        <Tag>
                            <Space>
                                <UserPhoto logoUri={item.member_logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                                {item.member_display_name}
                                <span>({item.has_evaluate ? "已投票" : "未投票"})</span>
                            </Space>
                        </Tag>
                    ))}
                </Space>
            ),
        },
        {
            title: "状态",
            width: 100,
            render: (_, row: EvaluateInfo) => {
                if (row.evaluate_state == EVALUATE_STATE_DRAFT) {
                    return "草稿";
                } else if (row.evaluate_state == EVALUATE_STATE_EVALUATE) {
                    return "评估中";
                } else if (row.evaluate_state == EVALUATE_STATE_FINISH) {
                    return "评估结束";
                }
                return "";
            },
        },
        {
            title: "操作",
            width: 120,
            render: (_, row: EvaluateInfo) => (
                <Space direction="vertical">
                    {row.evaluate_state == EVALUATE_STATE_DRAFT && (orgStore.curOrg?.owner_user_id == userStore.userInfo.userId ||
                        (orgStore.selfMember?.member_perm_info.manage_depart_ment_evaluate == true && orgStore.selfMember.parent_depart_ment_id == props.departMentId)) && (
                            <>
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setEditEvaluateInfo(row);
                                    }}>修改</Button>
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        changeState(row.evaluate_id, EVALUATE_STATE_EVALUATE);
                                    }}>转成评估状态</Button>
                            </>
                        )}
                    {row.evaluate_state == EVALUATE_STATE_EVALUATE && (row.user_perm.can_update || row.user_perm.can_view) && (
                        <>
                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setViewEvaluateInfo(row);
                            }}>查看评估</Button>
                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                changeState(row.evaluate_id, EVALUATE_STATE_FINISH);
                            }}>结束评估</Button>
                        </>
                    )}
                    {row.evaluate_state == EVALUATE_STATE_FINISH && (row.user_perm.can_update || row.user_perm.can_view) && (
                        <>
                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setViewEvaluateInfo(row);
                            }}>查看评估</Button>
                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                changeState(row.evaluate_id, EVALUATE_STATE_EVALUATE);
                            }}>转成评估状态</Button>
                        </>
                    )}
                    {row.user_perm.can_remove == true && (
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} danger
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveEvaluateInfo(row);
                            }}>删除评估</Button>
                    )}
                </Space>
            ),
        }
    ];

    useEffect(() => {
        if (curPage != 0) {
            setCurPage(0);
        }
    }, [orgStore.curOrgId, props.departMentId, props.memberUserId, props.dataVersion]);


    useEffect(() => {
        if (orgStore.curOrgId != "") {
            loadEvalInfoList();
        }
    }, [orgStore.curOrgId, props.departMentId, props.memberUserId, props.dataVersion, curPage]);

    return (
        <>
            <Table rowKey="evaluate_id" dataSource={evalInfoList} columns={columns}
                pagination={{ current: curPage + 1, pageSize: PAGE_SIZE, total: totalCount, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }} />
            {editEvaluateInfo != null && (
                <EditEvalModal departMentId={props.departMentId} evalInfo={editEvaluateInfo} onCancel={() => setEditEvaluateInfo(null)}
                    onOk={() => onUpdate(editEvaluateInfo.evaluate_id).then(() => setEditEvaluateInfo(null))} />
            )}
            {removeEvaluateInfo != null && (
                <Modal open title="删除评估" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveEvaluateInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeEval();
                    }}>
                    是否删除评估&nbsp;{removeEvaluateInfo.evaluate_title}&nbsp;?
                </Modal>
            )}
            {viewEvaluateInfo != null && (
                <ViewEvalModal
                    evalInfo={viewEvaluateInfo}
                    onClose={() => setViewEvaluateInfo(null)}
                    onChange={() => onVoteChange()}
                />
            )}
        </>
    );
};

export default observer(EvalList);